/**
 * @program: LeetCode
 * @description: LeetCode : 98. 验证二叉搜索树
 * @author: WXY
 * @create: 2023-01-02 17:02
 * @Version 1.0
 **/
public class num098_isValidBST {
    public boolean isValidBST(TreeNode root) {
        Info ans = process(root);
        return ans.isBST;
    }

    private Info process(TreeNode node) {
        if (node == null) return null;

        Info leftInfo = process(node.left);
        Info rightInfo = process(node.right);

        int max = node.val;
        int min = node.val;
        if (leftInfo != null) {
            max = Math.max(min, leftInfo.max);
            min = Math.min(min, leftInfo.min);
        }
        if (rightInfo != null) {
            max = Math.max(max, rightInfo.max);
            min = Math.min(min, rightInfo.min);
        }
        boolean isBST = false;
        if (
                (leftInfo != null ? leftInfo.isBST : true) &&
                        (rightInfo != null ? rightInfo.isBST : true) &&
                        (leftInfo != null ? leftInfo.max < node.val : true) &&
                        (rightInfo != null ? rightInfo.min > node.val : true)
        ) {
            isBST = true;
        }
        return new Info(isBST, max, min);
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public class Info {
        boolean isBST;
        int max;
        int min;

        public Info(boolean isBST, int max, int min) {
            this.isBST = isBST;
            this.max = max;
            this.min = min;
        }
    }

}
